package com.atguigu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseApp;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.CommonUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;


import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by RUI on 2021/6/28 18:36
 */
public class DwmUvApp extends BaseApp {
    public static void main(String[] args) {
        new DwmUvApp().init(3001, 2, "DwmUvApp", "DwmUvApp", Constant.TOPIC_DWD_PAGE_LOG);
    }

    @Override
    public void run(StreamExecutionEnvironment env, DataStreamSource<String> sourceStream) {
        sourceStream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((data, ts) -> data.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {

                private SimpleDateFormat df;
                private ValueState<Long> firstVisitState;

                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("firstVisitState", Long.class));

                    df = new SimpleDateFormat("yyyy-MM-dd");
                }

                @Override
                public void process(String key, Context ctx, Iterable<JSONObject> elements, Collector<JSONObject> out) throws Exception {

                    //跨天问题
                    String today = df.format(ctx.window().getEnd());
                    String fir = df.format(firstVisitState.value() == null ? 0L : firstVisitState.value());

                    if (!today.equals(fir)) {
                        firstVisitState.clear();
                    }

                    if (firstVisitState.value() == null) {
                        List<JSONObject> list = CommonUtil.toList(elements);
                        JSONObject first = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        out.collect(first);
                        firstVisitState.update(first.getLong("ts"));
                    }

                }
            })
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_UV));

    }
}
